package com.filter;

import com.constant.RedisKey;
import com.po.UserPO;
import com.util.JSONUtils;
import com.util.RedisUtil;
import com.util.RestException;
import com.util.UserLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author linyukun
 * @date 2022/7/7 10:45
 */
@Component
public class TokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain filterChain) throws ServletException, IOException {
        String uesrToken = req.getHeader("userToken");
        logger.info("userToken:" + uesrToken);

        if(StringUtils.isNotBlank(uesrToken)){
            String tokenKey = RedisKey.LIBRARY_USER_TOKEN + uesrToken;
            String adminJson = redisUtil.get( tokenKey );//从token里面获取数据
            if(StringUtils.isNotBlank(adminJson)){
                UserPO userPO = JSONUtils.parse( adminJson , UserPO.class );
                try {
                    UserLocal.set(userPO);//存到线程的threadLoad里面去
                    filterChain.doFilter(req, resp);
                } finally {
                    UserLocal.clear();
                }
            }else{
                filterChain.doFilter(req, resp);
            }
        }else{
            filterChain.doFilter(req, resp);
        }

    }
}
